import {
  queryAllPermission,
  getDetail,
  addRole,
  editRole,
  getResource,
  getAppList
} from './roleAdminDetailServ.js'
import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge, get, set, concat } from 'lodash'
import { hashHistory } from 'dva/router'
import AppBus from 'utils/bus'

import menu from 'config/menu'     //菜单
import subElements from 'config/subElements'

function formatSubElements (subElements = {}, checkedArr = []) {
  let obj = {}
  for (let key in subElements) {
    let selectedRowKeys = []
    let list = subElements[key] || []
    list.map((item, index) => {
      item.key = item.code
      if (checkedArr.indexOf(item + '') > 0) {
        selectedRowKeys.push(key + '')
      }
    })
    obj[key] = {
      list: list,
      selectedRowKeys: [],
    }
  }
  return obj
}

const defultState = {
  loading: false,
  btnLoading: false,
  type: '',//edit编辑，detail详情，add新增
  detailData: {}, //详情数据
  menu: [], //菜单
  subElements: formatSubElements(cloneDeep(subElements)), //菜单
  isLeaf: false, //菜单
  curSubElements: [], //当前展示的按钮列表
  treeInfo: {//tree数据
    halfCheckedKeys: [],
    expandedKeys: [],
    autoExpandParent: true,
    checkedKeys: [],   //勾选复选框
    selectedKeys: [],  //节点获得焦点
  },
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          //每次进来页面更新数据 重置state
          dispatch({type: 'updateStore', payload: cloneDeep(defultState)})
          // 获取资源树
          dispatch({type: 'queryAllPermission', payload: {}})
          
          if (query.actionType == 'edit'||query.actionType == 'check') {
            // 获取详情
            dispatch({type: 'getDetail', payload: {type: query.actionType, id: query.id}})
          }
          //todo:确少一个获取应用权限的接口
          
        }
      })
    },
  },
  
  effects: {
    //查询操作
    * queryAllPermission ({payload}, {put, call, select}) {
      try {
        const {success, rows = []} = yield call(queryAllPermission, {...payload, pageSize: 10000})
        if (success) {
          // let {respDtoList, butonIdList} = data
          rows.map((item, index) => {
            item.key = item.permissionMenuId
          })
          yield put({type: 'updateStore', payload: {menu: rows || []}})
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取详情
    * getDetail ({payload}, {put, call, select}) {
      let {detailData, type, data, treeInfo, subElements} = yield select(state => state[tmpModule.namespace])
      // yield put({ type: 'updateStore', payload: { ...defultState } })
      try {
        let {data, success} = yield call(getDetail, parse({permissionRoleId: payload.id}))
        if (success) {
          detailData = data
          let {permissionMenuList = [], butonIdList = []} = data
          // 预处理已选中的菜单id
          let arr = []
          permissionMenuList.map((item, inidex) => {
            if (item) {
              item.id = item.permissionMenuId
              arr.push(item.permissionMenuId)
            }
          })
          
          treeInfo.checkedKeys = arr
          
          // 预处理已选中的按钮id
          for (let key in subElements) {
            if (permissionMenuList.indexOf(key + '') == -1) {
              break
            }
            let item = subElements[key] || {}
            let list = subElements[key]['list'] || []
            list.map((item_s, index) => {
              if (butonIdList.indexOf(item_s.code) > 0) {
                item.selectedRowKeys.push(item_s.code)
              }
            })
          }
          
        }
        yield put({type: 'updateStore', payload: {type: payload.type, detailData, subElements}})
      } catch (e) {
        console.error(e)
      }
    },
    
    * save ({payload}, {put, call, select}) {
      let {detailData, type, treeInfo, subElements} = yield select(state => state[tmpModule.namespace])
      let {checkedKeys = [],} = treeInfo || {}
      
      function formatSubElements (subElements = []) {
        let arr = []
        let selectedRowKeys = []
        for (let key in subElements) {
          if (checkedKeys.indexOf('' + key) > -1) {  //节点被勾选
            selectedRowKeys = get(subElements[key], `selectedRowKeys`, []) //已选中的按钮id
            arr = arr.concat(selectedRowKeys)
          }
        }
        return arr
      }
      
      let arr = formatSubElements(cloneDeep(subElements))
      try {
        let param = {
          permissionRoleId: detailData.permissionRoleId || undefined,
          name: String(detailData.name).trim(),
          remark: detailData.remark,
          permissionMenuId: checkedKeys,
          subElements: arr,
        }
        yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
        let {data, resultCode} = yield call(type == 'add' ? addRole : editRole, param)
        yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
        message.success('新增成功')
        let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
        AppBus.emit('closeTab', {
          key: urlArray[1],
          cbf: () => {
            hashHistory.push(urlArray[0])
          }
        })
      } catch (error) {
        console.error(error)
      }
    },
    * selectedKeysChange ({payload}, {put, select}) {
      let {subElements, treeInfo, curSubElements} = yield select(state => state[tmpModule.namespace])
      let {isLeaf, leafId} = treeInfo
      let {selectedRowKeys = []} = payload
      curSubElements = get(subElements, `${leafId}`, {})
      curSubElements.selectedRowKeys = selectedRowKeys
      yield put({type: 'updateStore', payload: {subElements, curSubElements}})
    },
  },
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
